package elec315.chatroom.client;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import elec315.chatroom.client.ui.ConsoleUI;
import elec315.chatroom.core.dispatcher.ClientMessageDispatcher;
import elec315.chatroom.core.processor.ClientMessageProcessor;
import elec315.chatroom.net.ClientSocketHandler;

public class ChatClient implements Runnable {

	private static final Log logger = LogFactory.getLog(ChatClient.class);

	private final String ip;
	private final int port;

	public ChatClient(String ip, int port) {
		super();
		this.ip = ip;
		this.port = port;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		Socket clientSocket;
		try {
			ExecutorService executorService = Executors.newFixedThreadPool(2);

			clientSocket = new Socket(ip, port);
			logger.info("Connected to server: " + ip + ":" + port);

			ClientSocketHandler clientSocketHandler = new ClientSocketHandler(clientSocket);
			ClientRequestHandler clientRequestHandler = new ClientRequestHandler(clientSocketHandler);
			// dependency problem
			ConsoleUI uiBuilder = new ConsoleUI(clientRequestHandler);
			clientSocketHandler.setMessageDispatcher(new ClientMessageDispatcher(new ClientMessageProcessor(uiBuilder)));
			
			executorService.execute(clientSocketHandler);
			executorService.execute(uiBuilder);
		} catch (UnknownHostException ex) {
			logger.error(ex, ex);
		} catch (IOException ex) {
			logger.error(ex, ex);
		}
	}
	
}
